<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        Add
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时段名称" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type" @click="handleUpdate(row)">{{ row.name }}</span>
<!--          <el-tag>{{ row.type | typeFilter }}</el-tag>-->
        </template>
      </el-table-column>

      <el-table-column  label="createdBy" width="150">
        <template slot-scope="{row}">
            {{row.createBy}}
          </template>
      </el-table-column>
<!--      <el-table-column label="Author" width="110px" align="center">-->
<!--        <template slot-scope="{row}">-->
<!--          <span>{{ row.author }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column v-if="showReviewer" label="Reviewer" width="110px" align="center">-->
<!--        <template slot-scope="{row}">-->
<!--          <span style="color:red;">{{ row.reviewer }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="Imp" width="80px">-->
<!--        <template slot-scope="{row}">-->
<!--          <svg-icon v-for="n in + row.importance" :key="n" icon-class="star" class="meta-item__icon" />-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="是否为默认时段" class-name="status-col" width="100">
        <template slot-scope="{row}">

            {{ row.default }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdate(row)">
            编辑详情
          </el-button>
          <el-button  size="mini" type="danger" @click="handleDelete(row,$index)">
            删除时段
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="120px" style="width: 400px; margin-left:50px;">
        <el-form-item label="营业时段名称" prop="title">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="早餐" >
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="60px" style="width: 400px;margin-left:0px;">
            <el-form-item label="时段" >
            <el-time-picker
            is-range
            v-model="temp.value1"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围">
          </el-time-picker>
            </el-form-item>
            <el-form-item label="定额" >
          <el-input-number v-model="temp.num11" :min="1" :max="1000" label="定额" size="small"></el-input-number>
            </el-form-item>
            <el-form-item label="限次" >
          <el-input-number v-model="temp.num12" :min="1" :max="10" label="限次"size="small"></el-input-number>
            </el-form-item>
          </el-form>
        </el-form-item>

        <el-form-item label="午餐" >
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="60px" style="width: 400px;margin-left:0px;">
            <el-form-item label="时段" >
              <el-time-picker
                is-range
                v-model="temp.value2"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="定额" >
              <el-input-number v-model="temp.num21" :min="1" :max="1000" label="定额" size="small"></el-input-number>
            </el-form-item>
            <el-form-item label="限次" >
              <el-input-number v-model="temp.num22" :min="1" :max="10" label="限次"size="small"></el-input-number>
            </el-form-item>
          </el-form>
        </el-form-item>

        <el-form-item label="晚餐" >
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="60px" style="width: 400px;margin-left:0px;">
            <el-form-item label="时段" >
              <el-time-picker
                is-range
                v-model="temp.value3"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="定额" >
              <el-input-number v-model="temp.num31" :min="1" :max="1000" label="定额" size="small"></el-input-number>
            </el-form-item>
            <el-form-item label="限次" >
              <el-input-number v-model="temp.num32" :min="1" :max="10" label="限次"size="small"></el-input-number>
            </el-form-item>
          </el-form>
        </el-form-item>

        <el-form-item label="夜宵" >
          <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="60px" style="width: 400px;margin-left:0px;">
            <el-form-item label="时段" >
              <el-time-picker
                is-range
                v-model="temp.value4"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                placeholder="选择时间范围">
              </el-time-picker>
            </el-form-item>
            <el-form-item label="定额" >
              <el-input-number v-model="temp.num41" :min="1" :max="1000" label="定额" size="small"></el-input-number>
            </el-form-item>
            <el-form-item label="限次" >
              <el-input-number v-model="temp.num42" :min="1" :max="10" label="限次"size="small"></el-input-number>
            </el-form-item>
          </el-form>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>

<!--    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">-->
<!--      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">-->
<!--        <el-table-column prop="key" label="Channel" />-->
<!--        <el-table-column prop="pv" label="Pv" />-->
<!--      </el-table>-->
<!--      <span slot="footer" class="dialog-footer">-->
<!--        <el-button type="primary" @click="dialogPvVisible = false">Confirm</el-button>-->
<!--      </span>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
  //import { fetchList, fetchPv, createArticle, updateArticle } from '@/api/article'
  //import waves from '@/directive/waves' // waves directive
  import { parseTime } from '@/utils'
  //import Pagination from '@/components/Pagination'
  import {getTimeList} from "@/api/consume"; // secondary package based on el-pagination

  const calendarTypeOptions = [
    { key: 'CN', display_name: 'China' },
    { key: 'US', display_name: 'USA' },
    { key: 'JP', display_name: 'Japan' },
    { key: 'EU', display_name: 'Eurozone' }
  ]

  // arr to obj, such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'ComplexTable',
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,
          name: '',
          value1: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
          num11: undefined,
          num12: undefined,
          value2: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
          num21: undefined,
          num22: undefined,
          value3: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
          num31: undefined,
          num32: undefined,
          value4: [new Date(2016, 9, 10, 8, 40), new Date(2016, 9, 10, 9, 40)],
          num41: undefined,
          num42: undefined,
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        dialogPvVisible: false,
        pvData: [],
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false,

      }
    },
    created() {
      this.getList()
    },
    methods: {
      getList() {
        this.listLoading = true
        getTimeList(this.listQuery).then(response => {
          this.list = response.data.items
          this.total = response.data.total

          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      // handleModifyStatus(row, status) {
      //   this.$message({
      //     message: '操作Success',
      //     type: 'success'
      //   })
      //   row.status = status
      // },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            // createArticle(this.temp).then(() => {
            //   this.list.unshift(this.temp)
            //   this.dialogFormVisible = false
            //   this.$notify({
            //     title: 'Success',
            //     message: 'Created Successfully',
            //     type: 'success',
            //     duration: 2000
            //   })
            // })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            // updateArticle(tempData).then(() => {
            //   const index = this.list.findIndex(v => v.id === this.temp.id)
            //   this.list.splice(index, 1, this.temp)
            //   this.dialogFormVisible = false
            //   this.$notify({
            //     title: 'Success',
            //     message: 'Update Successfully',
            //     type: 'success',
            //     duration: 2000
            //   })
            // })
          }
        })
      },
      handleDelete(row, index) {
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      },

      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
</script>
